package dao.video;

import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.VideoEntity;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@WebServlet(name = "showByType", urlPatterns = "/dao/aaa")
public class showByType extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query = em.createQuery("select v from VideoEntity v");
        List<VideoEntity> list = query.getResultList();

        List<Video> videoList = new ArrayList<>();
        for (int j=0; j<list.size(); j++) {
            Video video = new Video();
            video.setVid(String.valueOf(list.get(j).getVid()));
            video.setName(list.get(j).getName());
            video.setAuthor(""+list.get(j).getUid().getName());
            video.setIntroduce(list.get(j).getIntroduce());
            video.setTime(list.get(j).getTime());
            video.setType(""+list.get(j).getTid().getName());
            video.setViews(list.get(j).getViews());
            video.setAv(list.get(j).getAv());
            video.setImgUrl(list.get(j).getImgUrl().equals("")?"http://localhost:8080/img/default.jpg":list.get(j).getImgUrl());
            videoList.add(video);
        }
        Map<String,List<Video>> map = new HashMap<String,List<Video>>();
        for(Video v : videoList){
            if(map.get(v.getType())!=null){
                map.get(v.getType()).add(v);
            }else{
                List<Video> l = new ArrayList<Video>();
                l.add(v);
                map.put(v.getType(),l);
            }
        }
        System.out.println(JSON.toJSONString(map));
        response.getWriter().write(URLEncoder.encode(JSON.toJSONString(map),StandardCharsets.UTF_8));
    }
}
